package com.zaoke.web.component.controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zaoke.web.bo.food.Food;
import com.zaoke.web.bo.food.FoodNutrition;
import com.zaoke.web.bo.food.FoodPromotion;
import com.zaoke.web.bo.food.FoodTag;
import com.zaoke.web.bo.food.Nutrition;
import com.zaoke.web.bo.query.food.FoodQuery;
import com.zaoke.web.bo.query.food.FoodQueryDetail;
import com.zaoke.web.bo.query.food.FoodSave;
import com.zaoke.web.bo.query.food.PromotionQuery;
import com.zaoke.web.bo.query.food.PromotionSave;
import com.zaoke.web.service.food.FoodService;
import com.zaoke.web.utils.JacksonUtil;
import com.zaoke.web.utils.WebResponse;

@Controller
@RequestMapping("/food/")
public class FoodController {

	@Autowired
	private FoodService foodService;
	
	@RequestMapping(value="food-new.do",method = RequestMethod.GET)  
    public ModelAndView food(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		
		int type = Integer.valueOf(request.getParameter("type"));
		mav.setViewName("food-new");
		mav.addObject("type",type);
		return mav;
    }
	
	@RequestMapping(value="food-special-new.do",method = RequestMethod.GET)  
    public String special(HttpServletRequest request, HttpServletResponse response) {
		return "food-special-new";
    }
	
	@ResponseBody
	@RequestMapping(value="listFood.ajax",method = RequestMethod.POST) 
	public WebResponse<ArrayList<FoodQuery>> listFood(HttpServletRequest request, HttpServletResponse response)
	{
		WebResponse<ArrayList<FoodQuery>> wr = new WebResponse<ArrayList<FoodQuery>>();
		ArrayList<FoodQuery> foods = new ArrayList<FoodQuery>();
		Set<Food> activeFoods = foodService.getAllActiveFoods(false);
		
		if(activeFoods!=null && activeFoods.size()>0)
		{
			for(Food food : activeFoods)
			{
				FoodQuery query = new FoodQuery();
				query.setId(food.getId());
				query.setName(food.getName());
				query.setType(food.getType());
				foods.add(query);
			}
		}
		
		wr.setData(foods);
		return wr;
	}
	
	@ResponseBody
	@RequestMapping(value="listSpecial.ajax",method = RequestMethod.POST) 
	public WebResponse<ArrayList<PromotionQuery>> listSpecial(HttpServletRequest request, HttpServletResponse response)
	{
		WebResponse<ArrayList<PromotionQuery>> wr = new WebResponse<ArrayList<PromotionQuery>>();
		ArrayList<PromotionQuery> querys = new ArrayList<PromotionQuery>();
		List<FoodPromotion> activeFoods = foodService.getAllActivePromotions();
		
		
		
		if(activeFoods!=null && activeFoods.size()>0)
		{
			List<Long> foodids = new ArrayList<Long>();
			Map<Long,String> foodName = new HashMap<Long, String>();
			for(FoodPromotion promotion : activeFoods)
			{
				foodids.add(promotion.getFoodid());
				Set<Food> foods = foodService.getAllActiveFoods(false);
				if(foods!=null && foods.size()>0)
				{
					for(Food food : foods)
					{
						foodName.put(food.getId(), food.getName());
					}
				}
				
			}
			
			for(FoodPromotion promotion : activeFoods)
			{
				PromotionQuery query = new PromotionQuery();
				query.setCombomarginStr(new DecimalFormat("0.00").format(promotion.getComboMargin()));
				query.setId(promotion.getId());
				query.setFooddate(promotion.getPromotionDate());
				query.setFoodid(promotion.getFoodid());
				query.setFoodname(foodName.get(promotion.getFoodid()));
				query.setSinglemarginStr(new DecimalFormat("0.00").format(promotion.getSingleMargin()));
				querys.add(query);
			}
		}
		
		wr.setData(querys);
		return wr;
	}
	
	
	@ResponseBody
	@RequestMapping(value="listFoodDetail.ajax",method = RequestMethod.POST) 
	public WebResponse<ArrayList<FoodQueryDetail>> listFoodDetail(HttpServletRequest request, HttpServletResponse response)
	{
		WebResponse<ArrayList<FoodQueryDetail>> wr = new WebResponse<ArrayList<FoodQueryDetail>>();
		ArrayList<FoodQueryDetail> foods = new ArrayList<FoodQueryDetail>();
		Set<Food> activeFoods = foodService.getAllActiveFoods(true);
		
		if(activeFoods!=null && activeFoods.size()>0)
		{
			for(Food food : activeFoods)
			{
				FoodQueryDetail query = new FoodQueryDetail();
				query.setId(food.getId());
				query.setName(food.getName());
				query.setType(food.getType());
				query.setDesc(food.getDesc());
				if(food.getImage() != null)
					query.setImagepath("/img/" + food.getImage().getUrl());
				if(food.getImagepc() != null)
					query.setImagepathpc("/img/" + food.getImagepc().getUrl());
//				query.setPrice(food.getSalePrice()+"");
				query.setState(transState(food.getState()));
				query.setValue(transNutritions(food.getNutritions()));
				query.setTags(transTags(food.getTags()));
				query.setPrice(new DecimalFormat("0.00").format(food.getSalePrice()));
				query.setSequence(food.getSequence());
				foods.add(query);
			}
		}
		
		wr.setData(foods);
		return wr;
	}
	
	private String transTags(Collection<FoodTag> tags)
	{
		String res = "";
		if(tags!=null && tags.size()>0)
		{
			for(FoodTag tag : tags)
			{
				res += tag.getTag()+",";
			}
		}
		if(res!=null && !"".equals(res))
			return res.substring(0,res.length()-1);
		return res;
	}
	
	private String transNutritions(Collection<FoodNutrition> nutritions)
	{
		String res = "";
		if(nutritions!=null && nutritions.size()>0)
		{
			for(FoodNutrition nu : nutritions)
			{
				res += nu.getNutrition().getName()+":"+nu.getValue()+",";
			}
		}
		return res;
	}
	
	private String transState(int state)
	{
		if(state==Food.STATE_ACTIVE)
		{
			return "正常使用";
		}
		if(state==Food.STATE_INACTIVE)
		{
			return "停止使用";	
		}
		return "";
	}
	
	@ResponseBody
	@RequestMapping(value="saveFood.ajax",method = RequestMethod.POST) 
	public WebResponse<Boolean> newFood(HttpServletRequest request, HttpServletResponse response)
	{
		WebResponse<Boolean> wr = new WebResponse<Boolean>();
		FoodSave input;
		try {
			input = JacksonUtil.readObj(request.getInputStream(), FoodSave.class);
			wr.setData(foodService.newFood(input));
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return wr;
	}
	
	@ResponseBody
	@RequestMapping(value="saveSpecial.ajax",method = RequestMethod.POST) 
	public WebResponse<Boolean> newPecial(HttpServletRequest request, HttpServletResponse response)
	{
		WebResponse<Boolean> wr = new WebResponse<Boolean>();
		PromotionSave input;
		try {
			input = JacksonUtil.readObj(request.getInputStream(), PromotionSave.class);
			wr.setData(foodService.newPromotion(input));
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return wr;
	}
	
	
	@ResponseBody
	@RequestMapping(value="updateSpecial.ajax",method = RequestMethod.POST) 
	public WebResponse<Boolean> updateSpecial(HttpServletRequest request, HttpServletResponse response)
	{
		WebResponse<Boolean> wr = new WebResponse<Boolean>();
		PromotionSave input;
		try {
			input = JacksonUtil.readObj(request.getInputStream(), PromotionSave.class);
			wr.setData(foodService.updatePromotion(input));
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return wr;
	}
	
	
	@ResponseBody
	@RequestMapping(value="updateFood.ajax",method = RequestMethod.POST) 
	public WebResponse<Boolean> updateFood(HttpServletRequest request, HttpServletResponse response)
	{
//		System.out.println("111111111111111111111");
		WebResponse<Boolean> wr = new WebResponse<Boolean>();
		FoodSave input;
		try {
//			System.out.println("22222222222222222222222222");
			input = JacksonUtil.readObj(request.getInputStream(), FoodSave.class);
//			System.out.println("3333333333333333333333333");
			wr.setData(foodService.updateFood(input));
//			System.out.println("444444444444444444444444");
		} catch (JsonParseException e) {
			e.printStackTrace();
//			System.out.println("7777777777777777777");
		} catch (JsonMappingException e) {
			e.printStackTrace();
//			System.out.println("888888888888888888888888888888");
		} catch (IOException e) {
			e.printStackTrace();
//			System.out.println("999999999999999999999999999");
		}
//		System.out.println("6666666666666666666666666666");
		return wr;
	}
	
	
	@RequestMapping(value="food-mod.do",method = RequestMethod.GET)  
    public ModelAndView foodmod(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		Long foodid = Long.valueOf(request.getParameter("foodid"));
		mav.setViewName("food-mod");
		FoodSave save = new FoodSave();
		Food food = foodService.getFoodById(foodid,true);
		if(food!=null)
		{
			Set<FoodNutrition> nutritions = food.getNutritions();
			Map<String,String> nuMap = new HashMap<String, String>();
			for(FoodNutrition nu : nutritions)
			{
				nuMap.put(nu.getNutrition().getName(), nu.getValue());
			}
			save.setCalorie(nuMap.get(Nutrition.calorie));
			save.setCarbo(nuMap.get(Nutrition.carbo));
			save.setDf(nuMap.get(Nutrition.df));
			save.setFat(nuMap.get(Nutrition.fat));
			save.setMineral(nuMap.get(Nutrition.mineral));
			save.setProtein(nuMap.get(Nutrition.protein));
			save.setValue(nuMap.get(Nutrition.value));
			save.setVitamin(nuMap.get(Nutrition.vitamin));
			save.setDesc(food.getDesc());
			List<FoodTag> tags = food.getTags();
			if(tags!=null && tags.size()>0)
			{
				int size = tags.size();
				if(size>0)
					save.setFlag1(tags.get(0).getTag());
				if(size>1)
					save.setFlag2(tags.get(1).getTag());
				if(size>2)
					save.setFlag3(tags.get(2).getTag());
				if(size>3)
					save.setFlag4(tags.get(3).getTag());
				if(size>4)
					save.setFlag5(tags.get(4).getTag());
			}
			if(food.getImage() != null)
				save.setImage(food.getImage().getContent());
			if(food.getImagepc() != null)
				save.setImagepc(food.getImagepc().getContent());
			save.setName(food.getName());
			save.setPrice(food.getSalePrice());
			save.setState(food.getState());
			save.setType(food.getType());
			save.setFoodid(foodid);
			save.setSequence(food.getSequence());
		}
		
		mav.addObject("food",save);
		return mav;
    }
	
	
	@RequestMapping(value="food-special-mod.do",method = RequestMethod.GET)  
    public ModelAndView foodspecialmod(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		Long id = Long.valueOf(request.getParameter("id"));
		FoodPromotion pro = foodService.getPromotionById(id);
		
		PromotionQuery query = new PromotionQuery();
		query.setCombomarginStr(new DecimalFormat("0.00").format(pro.getComboMargin()));
		query.setFoodid(pro.getFoodid());
		query.setFooddate(pro.getPromotionDate());
		query.setId(id);
		query.setSinglemarginStr(new DecimalFormat("0.00").format(pro.getSingleMargin()));
		
		mav.setViewName("food-special-mod");
		mav.addObject("special",query);
		return mav;
    }
	
	
	
	@RequestMapping(value="food-del.do",method = RequestMethod.GET)
	public void fooddel(HttpServletRequest request, HttpServletResponse response)
	{
		Long foodid = Long.valueOf(request.getParameter("foodid"));
		
		foodService.deleteFood(foodid);
	}
	
	@RequestMapping(value="food-special-del.do",method = RequestMethod.GET)
	public void specialdel(HttpServletRequest request, HttpServletResponse response)
	{
		Long id = Long.valueOf(request.getParameter("id"));
		
		foodService.deletePromotion(id);
	}
	
	
}
